<template>
  <div >
    <el-row v-if="optType != 'view'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:issueother:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:issueother:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wm:issueother:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="issuelineList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="产品物料编码" width="100" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
      <el-table-column label="产品物料名称" width="120px" align="center" prop="itemName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>

      <el-table-column label="品牌" align="center" prop="itemBrand"/>
      <el-table-column label="颜色" align="center" prop="itemColor"/>
      <el-table-column label="技术要求" align="center" prop="itemTechReq"/>
      <el-table-column label="型号" align="center" prop="itemModel"/>
      <el-table-column label="批次号" align="center" prop="batchCode" :show-overflow-tooltip="true"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName" :show-overflow-tooltip="true"/>
      <el-table-column label="库区名称" align="center" prop="locationName" :show-overflow-tooltip="true"/>
      <el-table-column label="库位名称" align="center" prop="areaName" :show-overflow-tooltip="true"/>
      <el-table-column
        v-for="col in columnsConfig"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :align="col.align"
        v-if="col.show">
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="单价（主）" align="center" prop="price" fixed="right">
        <template slot-scope="scope">
          <!--          {{ scope.row.price !== null && scope.row.price !== undefined ? scope.row.price : 0 }}-->
          {{ scope.row.price}}
        </template>
      </el-table-column>
      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure"  fixed="right"/>
      <el-table-column label="出库数量（主）" align="center" prop="quantityIssued" fixed="right">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.quantityIssued }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="单位（辅）" align="center" prop="storageUnit"  fixed="right"/>
      <el-table-column label="出库数量（辅）" align="center"   prop="storageUnitquantity" fixed="right">
        <template slot-scope="scope">
          <el-tag type="success" v-if="'Y' == scope.row.enableMultiUnit">{{ scope.row.storageUnitquantity }}</el-tag>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" v-if="optType != 'view'" width="180px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="optType != 'view'"
            v-hasPermi="['wm:issueother:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="optType != 'view'"
            v-hasPermi="['wm:issueother:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改其他出库单行对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <div class="dashed-container">
          <div class="dashed-title">基础信息</div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="物料编码" prop="itemCode">
                <el-input v-model="form.itemCode" readonly="readonly" placeholder="请选择产品物料编码">
                  <el-button slot="append" @click="handleSelectStock" icon="el-icon-search"></el-button>
                </el-input>
              </el-form-item>
              <StockSelect ref="stockSelect"
                           @onSelected="onStockSelected"></StockSelect>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料名称" prop="itemName">
                <el-input v-model="form.itemName" readonly="readonly"/>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="批次号" prop="batchCode">
                <el-input v-model="form.batchCode" readonly="readonly"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="规格型号" prop="specification">
                <el-input v-model="form.specification" readonly="readonly" type="textarea"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="dashed-container">
          <div class="dashed-title">单位信息</div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单价（主）" prop="price">
                <el-input-number  v-model="form.price" placeholder="请输入价格" style="width: 100%" readonly="readonly" :min="0"/>
              </el-form-item>
            </el-col>
          </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位（主）" prop="unitOfMeasure" >
              <el-input v-model="form.unitOfMeasure" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库数量（主）" prop="quantityIssued" label-width="100" style="width: 100%">
              <el-input-number :min=0  v-model="form.quantityIssued"  @change="handleChangeZhu" placeholder="请输入出库数量" />
            </el-form-item>
          </el-col>

        </el-row>
          <el-row :gutter="20" v-if="enableMultiUnit === 'Y'">
            <el-col :span="12">
              <el-form-item label="单位（辅）" prop="storageUnit" >
                <el-input v-model="form.storageUnit" readonly="readonly" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库数量（辅）" prop="storageUnitquantity" label-width="100" style="width: 100%">
                <el-input-number :min=0  v-model="form.storageUnitquantity" @change="handleChangeFu" placeholder="请输入出库数量"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="enableMultiUnit === 'Y'">
            <el-col :span="12">
              <el-form-item label="换算方式" prop="storageUnitType">
                <el-input :value="form.storageUnitType === 'fixed' ? '固定' : '浮动'"  readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="换算比例" prop="storageRatio">
                <el-input-number
                  :min="0"
                  v-model="form.storageRatio"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="dashed-container">
          <div class="dashed-title">仓库信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库区名称" prop="locationName">
              <el-input v-model="form.locationName" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位名称" prop="areaName">
              <el-input v-model="form.areaName" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        </div>
        <div class="dashed-container">
          <div class="dashed-title">其他信息</div>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addIssueline, delIssueline, getIssueline, listIssueline, updateIssueline } from "@/api/mes/wm/issuelineother";
import StockSelect from "@/components/stockSelect/single.vue"
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
import {getMdItem} from "@/api/mes/md/mdItem";
import Template from "@/views/print/printtemplate/list.vue";

export default {
  name: "Issueline",
  components: {Template, StockSelect},
  props: {
    optType: null,
    issueId: null,
    warehouseId: null,
    locationId: null,
    areaId: null,
    workorderId: null,
    itemCode: null,
  },
  data() {
    return {
      enableMultiUnit:'N',
      columnsConfig:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 其他出库单行表格数据
      issuelineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        issueId: this.issueId,
        workorderId: this.workorderId,
        itemId: null,
        itemCode: this.itemCode,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityIssued: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          {required: true, message: "产品物料不能为空", trigger: "blur"}
        ],
        quantityIssued: [
          {required: true, message: "出库数量不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getItemBase()
  },
/*  //不用监控这个了，有个弊端 比如固定 固定换算率33 主单位写20  辅单位算出来就0.6060606 这就又触发了辅单位变动，就又用0.6060606*33=19.9999998 就有不是20 了，所以不用这个了， 直接写@chang 事件里
  watch: {
    //浮动就根据两个数量计算出浮动率就可以了

    'form.storageUnitquantity'() {
      console.log("watch 库存单位数量",this.form.storageUnitquantity)
      if (this.form.storageUnitType === 'fixed') {
        this.handleFixedCalculate("storage");
      } else if (this.form.storageUnitType === 'float') {
        this.handleFloatCalculate();// 明确指定触发源
      }
    },
    'form.quantityIssued' : function () {
      if (this.form.storageUnitType === 'fixed') {
        this.handleFixedCalculate("main");
      } else if (this.form.storageUnitType === 'float') {
        this.handleFloatCalculate();// 明确指定触发源
      }

    },
  },*/
  methods: {
    /** 查询其他出库单行列表 */
    getList() {
      this.loading = true;
      listIssueline(this.queryParams).then(response => {
        this.issuelineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    handleChangeZhu(value){
      if('Y' == this.enableMultiUnit) {
        if (this.form.storageUnitType === 'fixed') {
          // 库存单位数量=主数量 / 换算比例
          this.form.storageUnitquantity = parseFloat(
            (this.form.quantityIssued / this.form.storageRatio).toFixed(7)
          );
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (this.form.storageUnitType === 'float') {
          this.handleFloatCalculate()
        }
        if (value > this.form.quantityMax) {
          this.$modal.msgError("当前出库数量（主）大于库存数量，请修改，否则将无法出库");
          return
        }
      }
    },
    handleChangeFu(){
      if (this.form.storageUnitType === 'fixed') {
        // 主数量 = 库存单位数量 * 换算比例
        this.form.quantityIssued = parseFloat(
          (this.form.storageUnitquantity * this.form.storageRatio).toFixed(7)
        );
      }
      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (this.form.storageUnitType === 'float') {
        this.handleFloatCalculate()
      }
      if(this.form.quantityIssued > this.form.quantityMax){
        this.$modal.msgError("当前出库数量（主）大于库存数量，请修改，否则将无法出库");
        return
      }
    },
  /*  handleFixedCalculate(triggerSource) {
      if (triggerSource === 'main'){
        // 库存单位数量=主数量 / 换算比例
        this.form.storageUnitquantity = parseFloat(
          (this.form.quantityIssued / this.form.storageRatio).toFixed(7)
        );
      }

      if (triggerSource === 'storage'){
        // 主数量 = 库存单位数量 * 换算比例
        this.form.quantityIssued = parseFloat(
          (this.form.storageUnitquantity * this.form.storageRatio).toFixed(7)
        );
      }
        if(this.form.quantityIssued > this.form.quantityMax){
          this.$modal.msgError("当前出库数量（主）大于库存数量，请修改，否则将无法出库");
          return
        }


      console.log("nnnnnn",this.form.quantityIssued)
    },*/
    handleFloatCalculate(triggerSource) {
      //浮动就根据两个数量计算出浮动率就可以了
      if (this.form.storageUnitType !== 'float') return;

        if (this.form.storageUnitquantity > 0 && this.form.quantityIssued > 0) {
          console.log("mmmmmmmmmmmm")
          // 计算新换算比例 = 主数量 / 库存单位数量
          this.form.storageRatio = parseFloat(
            (this.form.quantityIssued / this.form.storageUnitquantity).toFixed(4)
          );
        }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        issueId: this.issueId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityIssued: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        storageUnitType:null,
        storageUnit:null,
        storageRatio:0,
        storageUnitquantity:0,
        price:null,
        enableMultiUnit:null
      };
      this.resetForm("form");
      this.enableMultiUnit=null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加其他出库单行";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids
      getIssueline(lineId).then(response => {
        this.enableMultiUnit=response.data.enableMultiUnit
        this.form.enableMultiUnit=response.data.enableMultiUnit
        this.form = response.data;
        this.open = true;
        this.title = "修改其他出库单行";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs[ "form" ].validate(valid => {
        if (valid) {
          if(this.form.quantityIssued <= 0){
            this.$modal.msgError("出库数量（主）必须大于0");
            return
          }
          if(this.form.quantityIssued > this.form.quantityMax){
            this.$modal.msgError("当前出库数量（主）大于库存数量，请修改，否则将无法出库");
            return
          }
          if(this.enableMultiUnit =='Y'){
            if(this.form.storageUnitquantity <= 0){
              this.$modal.msgError("出库数量（辅）必须大于0");
              return
            }
          }
          if (this.form.lineId != null) {
            updateIssueline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIssueline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除其他出库单行编号为"' + lineIds + '"的数据项？').then(function () {
        return delIssueline(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleSelectStock() {
      this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();
    },
    //物料选择弹出框
    onStockSelected(obj) {
      if (obj != undefined && obj != null) {
        console.log("111111",obj)
        this.form.materialStockId = obj.materialStockId;
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
        this.form.batchCode = obj.batchCode;
        this.form.warehouseId = obj.warehouseId;
        this.form.warehouseCode = obj.warehouseCode;
        this.form.warehouseName = obj.warehouseName;
        this.form.locationId = obj.locationId;
        this.form.locationCode = obj.locationCode;
        this.form.locationName = obj.locationName;
        this.form.areaId = obj.areaId;
        this.form.areaCode = obj.areaCode;
        this.form.areaName = obj.areaName;
        this.form.quantityIssued = obj.quantityOnhand;
        this.form.quantityMax = obj.quantityOnhand;
        this.form.price = obj.price
        getMdItem(obj.itemId).then(response => {
          this.enableMultiUnit=response.data.enableMultiUnit
          this.form.enableMultiUnit=response.data.enableMultiUnit
          this.form.storageUnit=response.data.storageUnit
          this.form.storageUnitType=response.data.storageUnitType
          this.form.storageRatio=response.data.storageRatio
        })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/issueline/export', {
        ...this.queryParams
      }, `issueline_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.dashed-container {
  position: relative;
  border: 1px dashed #999;
  border-radius: 4px;
  padding: 16px;
  margin: 24px 0;
}

.dashed-title {
  position: absolute;
  top: -10px;
  left: 12px;
  background: white;
  padding: 0 8px;
  color: #666;
  font-size: 12px;
}
</style>
